package com.loe.ui

import android.content.res.Resources
import com.quickjs.*

var JSObject?.key: String?
    get() = this?.getString("key")
    set(value)
    {
        this?.set("key", value)
    }

/** 注册js方法 */
fun JSObject.registerFun(name: String, onFun: (args: JSArray) -> Unit): JSFunction
{
    return registerJavaMethod(
        JavaVoidCallback
        { _, args ->
            onFun(args)
        }, name
    )
}

/** 注册js回调方法 */
fun JSObject.registerFunReturn(name: String, onFun: (args: JSArray) -> Any?): JSFunction
{
    return registerJavaMethod(
        JavaCallback
        { _, args ->
            return@JavaCallback onFun(args)
        }, name
    )
}


fun dp(px: Double): Int
{
    return (px / Resources.getSystem().displayMetrics.density + 0.5).toInt()
}

fun dp(px: Int): Int
{
    return (px / Resources.getSystem().displayMetrics.density + 0.5).toInt()
}


inline fun <T> JSArray?.forEach(action: (T) -> Unit)
{
    if (this != null) for (i in 0 until length()) action(get(i) as T)
}

fun <T> JSArray?.toList(): ArrayList<T>
{
    val list = ArrayList<T>()
    if (this == null) return list
    for (i in 0 until length())
    {
        list.add(get(i) as T)
    }
    return list
}

fun JSObject?.gotString(name: String, def: String = ""): String
{
    return this?.getString(name) ?: def
}

inline fun JSObject.gotHasString(key: String, onValue: (value: String)->Unit)
{
    if(contains(key)) onValue(getString(key))
}

fun JSObject?.gotInt(name: String, def: Int = 0): Int
{
    if(this?.contains(name) == false) return def
    return this?.getInteger(name) ?: def
}

inline fun JSObject.gotHasInt(key: String, onValue: (value: Int)->Unit)
{
    if(contains(key)) onValue(getInteger(key))
}

fun JSObject?.gotBoolean(name: String, def: Boolean = false): Boolean
{
    if(this?.contains(name) == false) return def
    return this?.getBoolean(name) ?: def
}

inline fun JSObject.gotHasBoolean(key: String, onValue: (value: Boolean)->Unit)
{
    if(contains(key)) onValue(getBoolean(key))
}

fun JSObject?.gotDouble(name: String, def: Double = 0.0): Double
{
    return this?.getDouble(name) ?: def
}

inline fun JSObject.gotHasDouble(key: String, onValue: (value: Double)->Unit)
{
    if(contains(key)) onValue(getDouble(key))
}

fun JSObject?.gotObject(name: String): JSObject
{
    return this?.getObject(name) ?: JSObject(jsContext)
}

inline fun JSObject.gotHasObject(key: String, onValue: (value: JSObject)->Unit)
{
    if(contains(key)) onValue(getObject(key))
}

fun JSObject?.gotArray(name: String): JSArray
{
    return this?.getArray(name) ?: JSArray(jsContext)
}

inline fun JSObject.gotHasArray(key: String, onValue: (value: JSArray)->Unit)
{
    if(contains(key)) onValue(getArray(key))
}

inline fun JSObject.gotHasFunction(key: String, onValue: (value: JSFunction)->Unit)
{
    if(contains(key)) onValue(get(key) as JSFunction)
}

inline fun JSObject.gotHas(key: String, onValue: (value: Any)->Unit)
{
    if(contains(key)) onValue(get(key))
}